/** 
 * 地址编辑
 * 
 */

import { InputItem, List, TextareaItem, Toast, Picker, Button } from 'antd-mobile';
import { decorator } from 'grey-react-box'
import React from 'react';
import style from './style.module.scss';
import Panel from 'components/Panel';
import { createForm } from 'rc-form';
// import { district } from 'antd-mobile-demo-data';
import { server } from 'server';
import history from 'router/history'
import { withRouter } from 'react-router-dom';

const district = require('constant/area.json');

export default decorator<any, any>(createForm(), withRouter)(props => {

    const { onChange } = props;

    const { getFieldProps, getFieldError, getFieldsValue, validateFields } = props.form;

    const { save, saveloading } = props.location.state ? useAddressUpdate(props.location.state.id, onChange) : useAddressAdd(onChange)

    const onErrorClick = React.useCallback((e) => {
        Toast.fail(getFieldError(e).join('、'), 1);
    }, [getFieldError])

    const onSubmit = React.useCallback(() => {
        validateFields({ force: true }, (error) => {
            if (!error) {
                const values = getFieldsValue();
                save(values)
            }
        });
    }, [getFieldsValue, validateFields, save])

    return (
        <Panel className={style.body} >
            <form>
                <div className={style.cont} >
                    <List renderHeader={() => '收件人信息'}  >
                        <InputItem
                            {...getFieldProps('userName', {
                                initialValue: props.location.state?.userName,
                                rules: [
                                    { required: true, message: '请输入收件人' },
                                ],
                            })}
                            clear
                            error={!!getFieldError('userName')}
                            onErrorClick={() => { onErrorClick('userName') }}
                            placeholder="请输入收件人"
                        >姓名</InputItem>

                        <InputItem
                            {...getFieldProps('userPhone', {
                                initialValue: props.location.state?.userPhone,
                                rules: [{ required: true, message: '请输入手机号' }]
                            })}
                            clear
                            placeholder="请输入手机号"
                            error={!!getFieldError('userPhone')}
                            onErrorClick={() => { onErrorClick('userPhone') }}
                            type="phone"
                        >
                            手机号
                        </InputItem>

                        <Picker
                            title="选择地区"
                            data={district}
                            {...getFieldProps('userAddress', {
                                initialValue: props.location.state?.userAddress,
                                rules: [{ required: true, message: '请输入选择地区' }]
                            })}
                        >
                            <CustomChildren
                                error={!!getFieldError('userAddress')}
                                onErrorClick={() => { onErrorClick('userAddress') }}
                            >
                                地址
                            </CustomChildren>
                        </Picker>

                        <TextareaItem
                            {...getFieldProps('userDetailAddress', {
                                initialValue: props.location.state?.userDetailAddress,
                                rules: [{ required: true, message: '请输入详细地址' }]
                            })}
                            title="详细地址"
                            clear
                            placeholder="请输入详细地址"
                            error={!!getFieldError('userDetailAddress')}
                            onErrorClick={() => { onErrorClick('userDetailAddress') }}
                            data-seed="logId"
                            autoHeight
                        />
                    </List>
                </div>
                <Button type="primary" className={style.butt} onClick={onSubmit} loading={saveloading} >保存</Button>
            </form>
        </Panel >
    )
})

/** 地址新增的 hook */
const useAddressAdd = onChange => {

    const [saveloading, setSaveloading] = React.useState(false);

    const save = React.useCallback(async value => {
        setSaveloading(true);
        await (async () => {
            const url = `/medicine/address/add`;
            const ajax = await server.post(url, { ...value, userAddress: JSON.stringify(value.userAddress) }).end();
            if (ajax.err) return;
            Toast.success('添加成功！！！', 1);
            history.goBack();
        })()
        onChange()
        setSaveloading(false);
    }, [onChange])

    return {
        save,
        saveloading,
    }
}

/** 地址修改的 hook */
const useAddressUpdate = (id, onChange) => {

    const [saveloading, setSaveloading] = React.useState(false);

    const save = React.useCallback(async value => {
        setSaveloading(true);
        await (async () => {
            const url = `/medicine/address/update`;
            const ajax = await server.post(url, { ...value, id, userAddress: JSON.stringify(value.userAddress) }).end();
            if (ajax.err) return;
            Toast.success('添加成功！！！', 1);
            history.goBack();
        })()
        onChange()
        setSaveloading(false);
    }, [onChange, id])

    return {
        save,
        saveloading,
    }
}

const CustomChildren = props => {
    return (
        <InputItem
            placeholder="请选择地址"
            value={props.extra === '请选择' ? undefined : props.extra}
            onClick={props.onClick}
            error={props.error}
            onErrorClick={props.onErrorClick}
        >
            地址
        </InputItem>
    )
}